#include "mypostman.h"
#include "ui_mypostman.h"
#include "common.h"

MyPostman::MyPostman(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MyPostman)
{
    //setFixedSize(1280,800);

    ui->setupUi(this);
    DBinit();
    TableViewInit(); //初始化表头
    getUserList();   //获取用户列表
    getHistory();    //获取操作历史
    ui->checkBox_JSON->setDisabled(true);    //因为默认选择是GET，所以隐藏这个CheckBox
    ListViewSetupInit();        //初始化用户配置
    ui->listView_setup->setEditTriggers(QAbstractItemView::NoEditTriggers);

    ui->tab_Body->setDisabled(true);
    ui->tab_Headers->setDisabled(true);
    checkFlag = 0;   //默认未选择
    m_accessManager = new QNetworkAccessManager(this);
    connect(m_accessManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(httpReply(QNetworkReply*)));
    connect(m_accessManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(insertHis()));

    connect(m_accessManager,SIGNAL(finished(QNetworkReply *)),this,SLOT(getHistory()));
    ui->btn_save->setEnabled(false);                //功能还没做呢
}

MyPostman::~MyPostman()
{
    delete ui;
}


void MyPostman::on_btn_exit_clicked()
{
    close();
}

void MyPostman::DBinit()
{
    QString sql_User = "select * from User limit 1";
    QString sql_setting = "select * from Setting limit 1";
    QString sql_history = "select * from History limit 1";
    int hintflag = 0;//决定要不要给用户提示
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(sql_User))
    {
        hintflag = 1;
        //说明User表不存在
        QString sql_create_User = "CREATE TABLE User ("
                                 "UserName text(200) NOT NULL,"
                                 "PassWord TEXT(200),"
                                 "UpdateTime Text(50),"
                                 "PRIMARY KEY (UserName)"
                               ");";
        qDebug()<<"重建User表的sql为"<<sql_create_User;
        if(!sqlQuery.exec(sql_create_User))
        {
            qDebug()<<"重建sql出错"<<sqlQuery.lastError();
            QMessageBox::warning(nullptr,"警告","系统错误，请联系开发者!");
            return;
        }
    }
    if(!sqlQuery.exec(sql_setting))
    {
        //说明Setting表不存在
        hintflag = 1;
        QString sql_create_setting = "CREATE TABLE Setting ("
                                                           "ID TEXT(200) NOT NULL,"
                                                           "User TEXT(50),"
                                                           "ParamData BLOB(5000),"
                                                           "BodyData BLOB(5000),"
                                                           "HeaderData BLOB(5000),"
                                                           "Type TEXT(200),"
                                                           "HttpType TEXT(20),"
                                                           "Url TEXT(200),"
                                                           "CreateTime TEXT(20),"
                                                           "CheckFlag INTEGER,"
                                                           "PRIMARY KEY (ID)"
                                                         ");";

        qDebug()<<"重建Setting表的sql为"<<sql_create_setting;
        if(!sqlQuery.exec(sql_create_setting))
        {
            qDebug()<<"重建sql出错"<<sqlQuery.lastError();
            QMessageBox::warning(nullptr,"警告","系统错误，请联系开发者!");
            return;
        }
    }
    if(!sqlQuery.exec(sql_history))
    {
        //说明History表不存在
        hintflag = 1;
        QString sql_create_history = "CREATE TABLE History ("
                                                           "ID TEXT(200) NOT NULL,"
                                                           "User TEXT(50),"
                                                           "ParamData BLOB(5000),"
                                                           "BodyData BLOB(5000),"
                                                           "HeaderData BLOB(5000),"
                                                           "Type TEXT(200),"
                                                           "HttpType TEXT(20),"
                                                           "Url TEXT(200),"
                                                           "CreateTime TEXT(20),"
                                                           "CheckFlag INTEGER,"
                                                           "PRIMARY KEY (ID)"
                                                         ");";
        qDebug()<<"重建History表的sql为"<<sql_create_history;
        if(!sqlQuery.exec(sql_create_history))
        {
            qDebug()<<"重建sql出错"<<sqlQuery.lastError();
            QMessageBox::warning(nullptr,"警告","系统错误，请联系开发者!");
            return;
        }
    }

    if(hintflag == 1)
    {
        QMessageBox::about(nullptr,"提示","未找到数据库文件，已自动重建数据库");
    }

}

void MyPostman::on_btn_send_clicked()
{
    QString type = ui->comboBox_prot->currentText();
    QString BaseUrl = ui->comboBox_httpType->currentText();
    BaseUrl += ui->lineEdit_request->text();   //获取URL


    if(type == "POST")
    {
        RequestPOST(BaseUrl);
    }
    else if (type == "GET")
    {
        RequestGET(BaseUrl);
    }



}

void MyPostman::RequestPOST(QString BaseUrl)
{
    using namespace DJY;
    EasyQJson easy;
    QNetworkRequest request;

    request.setUrl(QUrl(BaseUrl));
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/json");
    QJsonObject obj1;
    if(checkFlag == 0)
    {
        int count = ui->tableView_Params->model()->rowCount();

        for(int i=0;i<count;i++)
        {
            QModelIndex name = ParamModel->index(i,0,QModelIndex());
            QModelIndex value = ParamModel->index(i,1,QModelIndex());
            QString strName = name.data().toString();
            QString strValue = value.data().toString();
            if(strName == "" || strName == nullptr)
            {
                continue;   //空数据不发给服务器
            }
            obj1.insert(strName,strValue);
        }
    }
    else
    {
        QString JsonString = ui->textEdit_Param->toPlainText();
        if(easy.isJson(JsonString) == false)
        {
            QMessageBox::warning(nullptr,"警告","输入的Json文本不合法\nJson的键值需要双引号");
            return;
        }

        obj1 = easy.ReadQStringReturnObject(JsonString);
    }

    QJsonDocument docu;
    docu.setObject(obj1);

    QByteArray postData = docu.toJson(QJsonDocument::Compact); //组给服务器的参数
    qDebug()<<postData<<__LINE__;

    m_accessManager->post(request,postData);
    qDebug()<<"postData = "<<postData;
}

void MyPostman::RequestGET(QString BaseUrl)
{
    QNetworkRequest request;
    int count = ui->tableView_Params->model()->rowCount();

    for(int i=0;i<count;i++)
    {
        QModelIndex name = ParamModel->index(i,0,QModelIndex());
        QModelIndex value = ParamModel->index(i,1,QModelIndex());
        QString strName = name.data().toString();
        QString strValue = value.data().toString();
        if(strName == "" || strName == nullptr)
        {
            continue;   //空数据不发给服务器
        }
        if(i==0)
        {
            BaseUrl += "?";

        }
        else
        {
            BaseUrl += "&";
        }
        BaseUrl += strName + "=" + strValue;
    }


    request.setUrl(QUrl(BaseUrl));
    qDebug()<<"GET: BaseUrl = "<<BaseUrl;
    m_accessManager->get(request);


}

void MyPostman::httpReply(QNetworkReply *reply)
{
    using namespace DJY;
    EasyQJson easy;
    if (reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();

        qDebug()<<bytes;
        QString string = QString::fromUtf8(bytes);
        if(easy.isJson(string) == true)
        {
            string = easy.JsonParse(string);    //既然是Json，就格式化一下
        }
        ui->textEdit_result->setText(string.toUtf8());
    }
    else
    {
        qDebug()<<"handle errors here";
        QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
        qDebug( "请求发生错误 code: %d %d\n", statusCodeV.toInt(),static_cast<int>(reply->error()));
        qDebug()<<(reply->errorString());
        ui->textEdit_result->setText(qPrintable(reply->errorString()));
    }
    reply->deleteLater();

}

//初始化TableView的表头
void MyPostman::TableViewInit()
{
    ParamModel = new QStandardItemModel;
    BodyModel = new QStandardItemModel;
    HeaderModel = new QStandardItemModel;
    SetupModel = new QStandardItemModel;
    QStringList head;
    head<<("key")<<("value");
    ParamModel->setHorizontalHeaderLabels(head);
    BodyModel->setHorizontalHeaderLabels(head);
    HeaderModel->setHorizontalHeaderLabels(head);


    QList<QStandardItem *>item;
    QStandardItem * item1 = new QStandardItem("");
    QStandardItem * item2 = new QStandardItem("");
    item<<item1<<item2;

    ui->tableView_Body->setModel(BodyModel);
    ui->tableView_Body->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    BodyModel->appendRow(item);

    ui->tableView_Params->setModel(ParamModel);
    ui->tableView_Params->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ParamModel->appendRow(item);

    ui->tableView_Headers->setModel(HeaderModel);
    ui->tableView_Headers->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    HeaderModel->appendRow(item);





    ui->stackedWidget_Head->setCurrentWidget(ui->page_tableHead);
    ui->stackedWidget_body->setCurrentWidget(ui->page_tableBody);
    ui->stackedWidget_param->setCurrentWidget(ui->page_tableParam);
}


//初始化表头，不创建空行
void MyPostman::TableViewInitEmpty()
{
    ParamModel = new QStandardItemModel;
    BodyModel = new QStandardItemModel;
    HeaderModel = new QStandardItemModel;
    QStringList head;
    head<<("key")<<("value");
    ParamModel->setHorizontalHeaderLabels(head);
    BodyModel->setHorizontalHeaderLabels(head);
    HeaderModel->setHorizontalHeaderLabels(head);


    ui->tableView_Body->setModel(BodyModel);
    ui->tableView_Body->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    ui->tableView_Params->setModel(ParamModel);
    ui->tableView_Params->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);


    ui->tableView_Headers->setModel(HeaderModel);
    ui->tableView_Headers->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    ui->stackedWidget_Head->setCurrentWidget(ui->page_tableHead);
    ui->stackedWidget_body->setCurrentWidget(ui->page_tableBody);
    ui->stackedWidget_param->setCurrentWidget(ui->page_tableParam);
}



//清空tableview的数据，不包括表头
void MyPostman::TableClear()
{
    ui->tableView_Body->clearSpans();
    ui->tableView_Params->clearSpans();
    ui->tableView_Headers->clearSpans();
}

void MyPostman::on_btn_add_clicked()
{
    int index = ui->tabWidget->currentIndex();

    QList<QStandardItem *>item;
    QStandardItem * item1 = new QStandardItem("");
    QStandardItem * item2 = new QStandardItem("");
    item<<item1<<item2;




    if(index == 0)  //Params
    {
        ParamModel->appendRow(item);
        ui->tableView_Params->repaint();
    }
    else if(index == 1)  //Body
    {
        BodyModel->appendRow(item);
        ui->tableView_Body->repaint();
    }
    else if(index == 2)  //Headers
    {
        HeaderModel->appendRow(item);
        ui->tableView_Headers->repaint();
    }

}

void MyPostman::on_tableView_Params_doubleClicked(const QModelIndex &index)
{
    //判断下是不是最后一个列
    int num = index.row();      //这是当前选中的行号
    QString str = index.data().toString();
    int Count = ui->tableView_Params->model()->rowCount();
    if(num == Count-1&& (str != "" || str != nullptr))
    {
        QList<QStandardItem *>item;
        QStandardItem * item1 = new QStandardItem("");
        QStandardItem * item2 = new QStandardItem("");
        item<<item1<<item2;
        ParamModel->appendRow(item);
        ui->tableView_Params->repaint();
    }



}

void MyPostman::on_tableView_Body_doubleClicked(const QModelIndex &index)
{
    //判断下是不是最后一个列
    int num = index.row();      //这是当前选中的行号
    int Count = ui->tableView_Body->model()->rowCount();
    QString str = index.data().toString();
    if(num == Count-1 && (str != "" || str != nullptr))
    {
        QList<QStandardItem *>item;
        QStandardItem * item1 = new QStandardItem("");
        QStandardItem * item2 = new QStandardItem("");
        item<<item1<<item2;
        BodyModel->appendRow(item);
        ui->tableView_Body->repaint();
    }
}

void MyPostman::on_tableView_Headers_doubleClicked(const QModelIndex &index)
{
    //判断下是不是最后一个列
    int num = index.row();      //这是当前选中的行号
    int Count = ui->tableView_Headers->model()->rowCount();
    QString str = index.data().toString();
    if(num == Count-1 &&  (str != "" || str != nullptr))
    {
        QList<QStandardItem *>item;
        QStandardItem * item1 = new QStandardItem("");
        QStandardItem * item2 = new QStandardItem("");
        item<<item1<<item2;
        HeaderModel->appendRow(item);
        ui->tableView_Headers->repaint();
    }
}

void MyPostman::on_btn_clear_clicked()
{
    int index = ui->tabWidget->currentIndex();
    if(index == 0)  //Params
    {
        ParamModel->clear();
        ui->tableView_Params->setModel(ParamModel);
        ui->tableView_Params->repaint();
    }
    else if(index == 1)  //Body
    {
        BodyModel->clear();
        ui->tableView_Params->setModel(BodyModel);
        ui->tableView_Body->repaint();
    }
    else if(index == 2)  //Headers
    {
        HeaderModel->clear();
        ui->tableView_Params->setModel(HeaderModel);
        ui->tableView_Headers->repaint();
    }
    TableViewInit();    //重新初始化表头

}

void MyPostman::on_btn_delete_clicked()
{
    int index = ui->tabWidget->currentIndex();

    if(index == 0)  //Params
    {
        int count = ui->tableView_Params->currentIndex().row();
        int rows = ParamModel->rowCount();
        if(rows == 1)
        {
            return;
        }
        ParamModel->removeRow(count);
        ui->tableView_Params->repaint();

    }
    else if(index == 1)  //Body
    {
        int count = ui->tableView_Body->currentIndex().row();
        int rows = BodyModel->rowCount();
        if(rows == 1)
        {
            return;
        }
        BodyModel->removeRow(count);
        ui->tableView_Body->repaint();
    }
    else if(index == 2)  //Headers
    {
        int count = ui->tableView_Headers->currentIndex().row();
        int rows = HeaderModel->rowCount();
        if(rows == 1)
        {
            return;
        }
        HeaderModel->removeRow(count);
        ui->tableView_Headers->repaint();
    }
}




void MyPostman::on_btn_changeUser_clicked()
{

    currentUser = ui->comboBox_User->currentText();
    if(currentUser == nullptr || currentUser == "")
    {
        QMessageBox::about(nullptr,"提示","当前用户为空，请先创建用户");
        return;
    }
    QDateTime now = QDateTime::currentDateTime();
    QString nowTime = now.toString("yyyyMMddhhmmss");
    QMessageBox::about(nullptr,"提示","切换用户成功，当前用户为:"+currentUser);
    QString sql_update = "update User set UpdateTime = '"+nowTime+"' where UserName = '"+currentUser+"'";
    qDebug()<<"更新用户的sql为"<<sql_update;
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(sql_update))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }

    getHistory();
    ListViewSetupInit();

}

//删除用户
void MyPostman::on_btn_delete_user_clicked()
{
    QString user = ui->comboBox_User->currentText();
    if(user==""||user == nullptr)
    {
        return;
    }
    QString sql_delete = "delete from User where UserName = '"+user+"'";
    QString sql_delete2 = "delete from Setting where User = '"+user+"'";
    QString sql_delete3= "delete from History where User = '"+user+"'";
    qDebug()<<"删除用户的sql为"<<sql_delete;
    qDebug()<<"删除用户的sql为"<<sql_delete2;
    qDebug()<<"删除用户的sql为"<<sql_delete3;
    if(QMessageBox::Yes == QMessageBox::warning(nullptr,"警告","真的要删除用户"+user+"吗？",
                                                QMessageBox::Yes|QMessageBox::No,QMessageBox::No))
    {
        QSqlQuery sqlQuery;
        if(!sqlQuery.exec(sql_delete))
        {
            QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");

        }
        else
        {
            if(!sqlQuery.exec(sql_delete))
            {
                QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");

            }
            else
            {
                if(!sqlQuery.exec(sql_delete3))
                {
                    QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
                }
                else
                {
                    getUserList();
                    getHistory();
                    ListViewSetupInit();
                }
            }


        }
    }
}

void MyPostman::on_btn_addNewUser_clicked()
{
    addNew = new AddNew(this,this);
    addNew->show();
}


//获取用户列表
void MyPostman::getUserList()
{
    QString getSql = "select UserName from User order by UpdateTime Desc";
    QSqlQuery sqlQuery;
    UserList.clear();
    ui->comboBox_User->clear();
    if(!sqlQuery.exec(getSql))
    {
        qDebug() << sqlQuery.lastError();

        currentUser = nullptr;
    }
    else
    {
        qDebug() << "获取用户信息的sql为"<<getSql;
        while(sqlQuery.next()){

            QString user = sqlQuery.value(0).toString();
            qDebug()<<"user:"<<user;
            UserList.append(user);
            ui->comboBox_User->addItem(user);
            qDebug()<<"UserList ="<<UserList;
        }
        currentUser = ui->comboBox_User->currentText();
    }
}


//记录操作历史
void MyPostman::insertHis()
{
    using namespace DJY;
    EasyQJson Easy;
    QString Url = ui->lineEdit_request->text(); //URL
    QString result = ui->textEdit_result->toPlainText();    //请求结果
    QDateTime now = QDateTime::currentDateTime();
    QString nowTime = now.toString("yyyy-MM-dd hh:mm:ss");
    QJsonObject Para,Body,Header;

    int ParaCount = ParamModel->rowCount();
    int BodyCount = BodyModel->rowCount();
    int HeadCount = HeaderModel->rowCount();
    if(checkFlag == 0)
    {
        for(int i=0;i<ParaCount;i++)
        {
            QModelIndex name = ParamModel->index(i,0);
            QModelIndex value = ParamModel->index(i,1);
            QString Name = name.data().toString();
            QString Value = value.data().toString();
            Para.insert(Name,Value);
        }
    }
    else
    {
        QString ParaJson = ui->textEdit_Param->toPlainText();
        ParaJson = Easy.JsonParse(ParaJson);
        Para = Easy.ReadQStringReturnObject(ParaJson);
    }

    for(int i=0;i<BodyCount;i++)
    {
        QModelIndex name = BodyModel->index(i,0);
        QModelIndex value = BodyModel->index(i,1);
        QString Name = name.data().toString();
        QString Value = value.data().toString();
        Body.insert(Name,Value);
    }
    for(int i=0;i<HeadCount;i++)
    {
        QModelIndex name = HeaderModel->index(i,0);
        QModelIndex value = HeaderModel->index(i,1);
        QString Name = name.data().toString();
        QString Value = value.data().toString();
        Header.insert(Name,Value);
    }
    QString ParaValue = Easy.readObjectReturnQString(Para);
    QString BodyValue = Easy.readObjectReturnQString(Body);
    QString HeaderValue = Easy.readObjectReturnQString(Header);
    QString propStr = ui->comboBox_prot->currentText();

    int httpType = ui->comboBox_httpType->currentIndex();
    int prop = 0;
    if(propStr == "GET")
    {
        prop = 0;
    }
    else
    {
        prop = 1;
    }

    QString ID = nowTime+"-"+ui->comboBox_prot->currentText()+"-"+ui->comboBox_httpType->currentText()+Url;     //拼接唯一键
    QString insert_sql = "insert into History(ID,User,ParamData,BodyData,HeaderData,Result,Type,HttpType,Url,CreateTime,CheckFlag) "
                         "values('"+ID+"','"+currentUser+"','"+ParaValue+"','"+BodyValue+"','"+HeaderValue+"','"+result+"',"
            +QString::number(httpType)+","+QString::number(prop)+",'"+Url+"','"+nowTime+"','"+QString::number(checkFlag)+"')";
    qDebug()<<"插入历史记录的sql为"<<insert_sql;
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(insert_sql))
    {
        qDebug() << sqlQuery.lastError();

    }
    else
    {
        qDebug() << "记录日志成功";

    }

}

void MyPostman::getHistory()
{
    QString sql_his = "select ID,CreateTime from History where User = '"+currentUser+"' order by CreateTime Desc limit 100 ";
    QSqlQuery sqlQuery;
    ui->listWidget_history->clear();
    if(!sqlQuery.exec(sql_his))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "getHistory success";

        while(sqlQuery.next())
        {
            ui->listWidget_history->addItem(sqlQuery.value(0).toString());


        }

    }
    ui->listWidget_history->repaint();
}


void MyPostman::ListViewSetupInit()
{
    QString sql_get = "select ID from Setting where User = '"+currentUser+"' order by CreateTime Desc";
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(sql_get))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "getHistory success";
        SetupModel->clear();        //先清空
        int count = 0;
        while(sqlQuery.next())
        {
            QList<QStandardItem *>item;
            QString Name = sqlQuery.value(0).toString();
            QStandardItem * item1 = new QStandardItem(Name);
            \
            item<<item1;
            SetupModel->insertRow(count,item);
            count++;
        }
        ui->listView_setup->setModel(SetupModel);
        ui->listView_setup->repaint();
    }
}


void MyPostman::on_listWidget_history_clicked(const QModelIndex &index)
{
    using namespace DJY;
    EasyQJson Easy;
    QString ID = index.data().toString();
    QString get_sql = "select ParamData,BodyData,HeaderData,Result,Type,HttpType,Url,checkFlag"
                      " from History where ID = '"+ID+"'";
    qDebug()<<"关联操作记录的sql为"<<get_sql;
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(get_sql))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "getHistory success";
        sqlQuery.next();

        ui->comboBox_prot->setCurrentIndex(sqlQuery.value(4).toInt());
        ui->comboBox_httpType->setCurrentIndex(sqlQuery.value(5).toInt());
        ui->textEdit_result->setText(sqlQuery.value(3).toString());
        ui->lineEdit_request->setText(sqlQuery.value(6).toString());
        ui->comboBox_prot->repaint();
        ui->comboBox_httpType->repaint();
        ui->textEdit_result->repaint();
        ui->lineEdit_request->repaint();

        QJsonObject Param = Easy.ReadQStringReturnObject(sqlQuery.value(0).toString());
        QJsonObject Body = Easy.ReadQStringReturnObject(sqlQuery.value(1).toString());
        QJsonObject Head = Easy.ReadQStringReturnObject(sqlQuery.value(2).toString());

        QStringList ParamKey = Param.keys();
        QStringList BodyKey = Body.keys();
        QStringList HeadKey = Head.keys();
        qDebug()<<"sqlQuery.value(0)"<<sqlQuery.value(0);
        qDebug()<<"Param = "<<Param;
        qDebug()<<"ParamKey = "<<ParamKey;
        ParamModel->clear();
        HeaderModel->clear();
        BodyModel->clear();
        TableViewInitEmpty();
        int check = sqlQuery.value(7).toInt();
        if(check == 1)
        {
            QString Json = sqlQuery.value(0).toString();
            Json = Easy.JsonParse(Json);
            ui->textEdit_Param->setText(Json);

        }
        else
        {
            for(int i=0;i<ParamKey.size();i++)
            {
                QString key = ParamKey[i];
                QString value = Param[key].toString();
                QList<QStandardItem *>item;
                QStandardItem * item1 = new QStandardItem(key);
                QStandardItem * item2 = new QStandardItem(value);
                item<<item1<<item2;
                ParamModel->appendRow(item);
            }
            ui->tableView_Params->repaint();

        }
        checkFlag = check;
        changeAsCheckFlag(check);


        for(int i=0;i<HeadKey.size();i++)
        {
            QString key = HeadKey[i];
            QString value = Head[key].toString();
            QList<QStandardItem *>item;
            QStandardItem * item1 = new QStandardItem(key);
            QStandardItem * item2 = new QStandardItem(value);
            item<<item1<<item2;
            HeaderModel->appendRow(item);
        }
        ui->tableView_Headers->repaint();


        for(int i=0;i<BodyKey.size();i++)
        {
            QString key = BodyKey[i];
            QString value = Body[key].toString();
            QList<QStandardItem *>item;
            QStandardItem * item1 = new QStandardItem(key);
            QStandardItem * item2 = new QStandardItem(value);
            item<<item1<<item2;
            BodyModel->appendRow(item);
        }
        ui->tableView_Body->repaint();

    }

}

void MyPostman::on_btn_delete_history_clicked()
{
    QModelIndex index = ui->listWidget_history->currentIndex();
    QString ID = index.data().toString();
    if(ID== nullptr|| ID=="")
    {
        return;
    }
    QString deleteSql = "delete from history where ID = '"+ID+"'";
    qDebug()<<"删除历史记录的sql为"<<deleteSql;
    QSqlQuery sqlQuery;

    if(QMessageBox::Yes == QMessageBox::warning(nullptr,"警告","确定要删除操作记录\n"+ID+"吗？",
                                                QMessageBox::Yes | QMessageBox::No, QMessageBox::No))
    {
        if(!sqlQuery.exec(deleteSql))
        {
            qDebug() << sqlQuery.lastError();

            QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
        }
        else
        {
            qDebug()<<"操作历史删除成功";
            getHistory();

        }
    }
    else
    {
        return;
    }


}


//点击按钮后，界面切换
void MyPostman::on_checkBox_JSON_clicked()
{
    if(ui->checkBox_JSON->isChecked())
    {

        checkFlag = 1;
    }
    else
    {

        checkFlag = 0;
    }
    changeAsCheckFlag(checkFlag);
    ui->checkBox_JSON->setEnabled(true);
    ui->checkBox_JSON->repaint();
}

void MyPostman::on_btn_addset_clicked()
{
    ui->stackedWidget_add->setCurrentWidget(ui->page_add);
}


void MyPostman::on_btn_add_cancel_clicked()
{
    ui->lineEdit_setupName->setText("");
    ui->stackedWidget_add->setCurrentWidget(ui->page_usual);
}

void MyPostman::on_btn_add_comfirm_clicked()
{
    using namespace DJY;
    EasyQJson Easy;
    QSqlQuery sqlQuery;
    QString setupName = ui->lineEdit_setupName->text();

    //先进行错误判断
    if(setupName == "" || setupName == nullptr)
    {
        QMessageBox::warning(nullptr,"警告","配置名称不能为空");
        return;
    }
    QString sql_count = "select count(1) from Setting where Id = '"+setupName+"'";
    if(!sqlQuery.exec(sql_count))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "getHistory success";
        sqlQuery.next();
        if(sqlQuery.value(0).toInt()!= 0 )
        {
            QMessageBox::warning(nullptr,"警告","配置名称重复");
            return;
        }
    }

    QString Url = ui->lineEdit_request->text(); //URL
    //QString result = ui->textEdit_result->toPlainText();    //请求结果
    QDateTime now = QDateTime::currentDateTime();
    QString nowTime = now.toString("yyyy-MM-dd hh:mm:ss");
    QJsonObject Para,Body,Header;

    int ParaCount = ParamModel->rowCount();
    int BodyCount = BodyModel->rowCount();
    int HeadCount = HeaderModel->rowCount();
    if(checkFlag == 1)
    {
        QString Json = ui->textEdit_Param->toPlainText();
        Json = Easy.JsonParse(Json);
        Para = Easy.ReadQStringReturnObject(Json);

    }
    else
    {
        for(int i=0;i<ParaCount;i++)
        {
            QModelIndex name = ParamModel->index(i,0);
            QModelIndex value = ParamModel->index(i,1);
            QString Name = name.data().toString();
            QString Value = value.data().toString();
            Para.insert(Name,Value);
        }
    }
    changeAsCheckFlag(checkFlag);
    for(int i=0;i<BodyCount;i++)
    {
        QModelIndex name = BodyModel->index(i,0);
        QModelIndex value = BodyModel->index(i,1);
        QString Name = name.data().toString();
        QString Value = value.data().toString();
        Body.insert(Name,Value);
    }
    for(int i=0;i<HeadCount;i++)
    {
        QModelIndex name = HeaderModel->index(i,0);
        QModelIndex value = HeaderModel->index(i,1);
        QString Name = name.data().toString();
        QString Value = value.data().toString();
        Header.insert(Name,Value);
    }
    QString ParaValue = Easy.readObjectReturnQString(Para);
    QString BodyValue = Easy.readObjectReturnQString(Body);
    QString HeaderValue = Easy.readObjectReturnQString(Header);

    int httpType = ui->comboBox_httpType->currentIndex();
    int prop = ui->comboBox_prot->currentIndex();
    QString sql_insert = "insert into Setting (ID,User,ParamData,BodyData,HeaderData,Type,HttpType,Url,"
                         "CreateTime,CheckFlag) values('"+setupName+"','"+currentUser+"','"+ParaValue+"',"
                                                                                                      "'"+BodyValue+"','"+HeaderValue+"','"+QString::number(prop)+"',"
                                                                                                                                                                  "'"+QString::number(httpType)+"','"+Url+"','"+nowTime+"','"+QString::number(checkFlag)+"')";
    if(!sqlQuery.exec(sql_insert))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "用户配置入库成功 success";
        ui->lineEdit_setupName->setText("");
        ui->stackedWidget_add->setCurrentWidget(ui->page_usual);
        ListViewSetupInit();

    }

}

void MyPostman::changeAsCheckFlag(int flag)
{
   if(flag == 0)
   {
       ui->checkBox_JSON->setChecked(false);
       ui->checkBox_JSON->setEnabled(false);
       ui->stackedWidget_param->setCurrentWidget(ui->page_tableParam);
       ui->btn_add->setEnabled(true);
       ui->btn_clear->setEnabled(true);
       ui->btn_delete->setEnabled(true);

   }
   else
   {
       ui->checkBox_JSON->setChecked(true);
       ui->checkBox_JSON->setEnabled(true);
       ui->stackedWidget_param->setCurrentWidget(ui->page_JsonParam);

       ui->btn_add->setEnabled(false);
       ui->btn_clear->setEnabled(false);
       ui->btn_delete->setEnabled(false);
   }
   ui->checkBox_JSON->repaint();
   ui->stackedWidget_param->repaint();
}


//点击了listView，从数据库读取预配置的请求
void MyPostman::on_listView_setup_clicked(const QModelIndex &index)
{
    using namespace DJY;
    EasyQJson Easy;
    QString ID = index.data().toString();
    QString get_sql = "select ParamData,BodyData,HeaderData,Type,HttpType,Url,checkFlag"
                      " from Setting where ID = '"+ID+"'";
    qDebug()<<"关联用户配置的sql为"<<get_sql;
    QSqlQuery sqlQuery;
    if(!sqlQuery.exec(get_sql))
    {
        qDebug() << sqlQuery.lastError();

        QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
    }
    else
    {
        qDebug() << "getHistory success";
        sqlQuery.next();

        ui->comboBox_prot->setCurrentIndex(sqlQuery.value(3).toInt());
        ui->comboBox_httpType->setCurrentIndex(sqlQuery.value(4).toInt());
        ui->textEdit_result->setText("");       //没有result
        ui->lineEdit_request->setText(sqlQuery.value(5).toString());
        ui->comboBox_prot->repaint();
        ui->comboBox_httpType->repaint();
        ui->textEdit_result->repaint();
        ui->lineEdit_request->repaint();

        QJsonObject Param = Easy.ReadQStringReturnObject(sqlQuery.value(0).toString());
        QJsonObject Body = Easy.ReadQStringReturnObject(sqlQuery.value(1).toString());
        QJsonObject Head = Easy.ReadQStringReturnObject(sqlQuery.value(2).toString());

        QStringList ParamKey = Param.keys();
        QStringList BodyKey = Body.keys();
        QStringList HeadKey = Head.keys();
        qDebug()<<"sqlQuery.value(0)"<<sqlQuery.value(0);
        qDebug()<<"Param = "<<Param;
        qDebug()<<"ParamKey = "<<ParamKey;
        ParamModel->clear();
        HeaderModel->clear();
        BodyModel->clear();
        TableViewInitEmpty();
        int flag = sqlQuery.value(6).toInt();
        if(flag == 0)
        {
            for(int i=0;i<ParamKey.size();i++)
            {
                QString key = ParamKey[i];
                QString value = Param[key].toString();
                QList<QStandardItem *>item;
                QStandardItem * item1 = new QStandardItem(key);
                QStandardItem * item2 = new QStandardItem(value);
                item<<item1<<item2;
                ParamModel->appendRow(item);
                ui->tableView_Params->repaint();
            }

        }
        else
        {
            QString Json = sqlQuery.value(0).toString();
            Json = Easy.JsonParse(Json);
            ui->textEdit_Param->setText(Json);
        }
        changeAsCheckFlag(flag);



        for(int i=0;i<HeadKey.size();i++)
        {
            QString key = HeadKey[i];
            QString value = Head[key].toString();
            QList<QStandardItem *>item;
            QStandardItem * item1 = new QStandardItem(key);
            QStandardItem * item2 = new QStandardItem(value);
            item<<item1<<item2;
            HeaderModel->appendRow(item);
        }
        ui->tableView_Headers->repaint();


        for(int i=0;i<BodyKey.size();i++)
        {
            QString key = BodyKey[i];
            QString value = Body[key].toString();
            QList<QStandardItem *>item;
            QStandardItem * item1 = new QStandardItem(key);
            QStandardItem * item2 = new QStandardItem(value);
            item<<item1<<item2;
            BodyModel->appendRow(item);
        }
        ui->tableView_Body->repaint();

    }

}

void MyPostman::on_btn_delete_set_clicked()
{
    QModelIndex index = ui->listView_setup->currentIndex();
    QString Name = index.data().toString();
    if(Name == ""||Name == nullptr)
    {
        return;
    }
    if(QMessageBox::Yes ==QMessageBox::warning(nullptr,"警告","确定要删除请求配置:"+Name+"吗?",
                                               QMessageBox::Yes|QMessageBox::No,QMessageBox::No))
    {
        QSqlQuery sqlQuery;
        QString sql_delete = "delete  from Setting where ID = '"+Name+"'";
        qDebug()<<"删除操作历史的sql为"<<sql_delete;
        if(!sqlQuery.exec(sql_delete))
        {
            qDebug() << sqlQuery.lastError();

            QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
        }
        else
        {
            ListViewSetupInit();
            ui->checkBox_JSON->setChecked(false);
            ui->checkBox_JSON->setEnabled(false);
            ui->stackedWidget_param->setCurrentWidget(ui->page_tableParam);
            checkFlag = 0;
            changeAsCheckFlag(checkFlag);
        }
    }


}

void MyPostman::on_btn_Listclear_clicked()
{
    if(QMessageBox::Yes ==QMessageBox::warning(nullptr,"警告","确定要删除所有的操作历史吗?",
                                               QMessageBox::Yes|QMessageBox::No,QMessageBox::No))
    {
        QSqlQuery sqlQuery;
        QString sql_delete = "delete  from History";
        qDebug()<<"删除操作历史的sql为"<<sql_delete;
        if(!sqlQuery.exec(sql_delete))
        {
            qDebug() << sqlQuery.lastError();

            QMessageBox::warning(nullptr,"提示","系统错误，请联系开发者!");
        }
        else
        {
            getHistory();

        }
    }
    else
    {
        return;
    }
}


//优化CheckBox按钮
void MyPostman::on_comboBox_prot_currentIndexChanged(int index)
{
    QString Type = ui->comboBox_prot->currentText();
    if(Type == "GET")       //GET请求隐藏
    {
        ui->checkBox_JSON->setDisabled(true);

    }
    else                    //POST请求显示
    {
        ui->checkBox_JSON->setDisabled(false);


    }
    ui->stackedWidget_param->setCurrentWidget(ui->page_tableParam); //都切换到table，而不是Json页面
    ui->checkBox_JSON->repaint();
    ui->stackedWidget_param->repaint();
}


